package com.tianpengtech.front.web.passport;

import com.jfinal.kit.HashKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.ehcache.CacheKit;
import com.tianpengtech.common.exception.ValidateException;
import com.tianpengtech.common.model.authenticate.Authenticate;
import com.tianpengtech.common.model.user.User;
import com.tianpengtech.common.util.SendSmsMsg;
import com.tianpengtech.common.validator.Validator;
import com.tianpengtech.common.validator.rules.string.StringLengthBetween;
import com.tianpengtech.common.validator.rules.string.StringMustBeMobile;
import com.tianpengtech.common.validator.rules.string.StringMustBeRequired;
import com.tianpengtech.front.web.login.LoginService;

/**
 * Created by ggd on 2017/5/28 0028.
 */
public class PassportService {
    public static final PassportService me = new PassportService();
    private final User userDao = User.dao;
    private final Authenticate authDao = Authenticate.dao;
    private final LoginService loginService = new LoginService();
    /**
     * 验证手机号码是否存在
     */
    public boolean isMobileExists(String mobile,Integer user_type){
        String sql =String.format("select * from %s where %s = ? and %s = ? and %s=?",new User().tableName(),User.MOBILE,User.DELETETAG,User.USER_TYPE);
        User user=userDao.findFirst(sql,mobile,User.DELETE_STATUS_NO,user_type);
        if (null == user){
            return false;
        }else{
            return true;
        }
    }


    /**
     * 验证用户ID是否存在
     */
    public boolean isUserIdExists(String id,Integer user_type){
        String sql =String.format("select * from %s where %s = ? and %s = ? and %s=?",new User().tableName(),User.ID,User.DELETETAG,User.USER_TYPE);
        User user=userDao.findFirst(sql,id,User.DELETE_STATUS_NO,user_type);
        if (null == user){
            return false;
        }else{
            return true;
        }
    }


    /**
     * 账户注册，hashedPass = sha256(32字符salt + pass)
     */
    public Ret reg(String mobile, String password,Integer user_type) {
        if (user_type==User.USER_TYPE_PROV){
            if (StrKit.isBlank(mobile) || StrKit.isBlank(password)) {
                return Ret.fail("msg", "手机号码或密码不能为空");
            }
            password = password.trim();
            mobile = mobile.trim();
        }
        if (mobile.contains(" ") || mobile.contains("　")) { // 检测是否包含半角或全角空格
            return Ret.fail("msg", "手机号码不能包含空格");
        }
        if (isMobileExists(mobile,user_type)) {
            return Ret.fail("msg", "手机号码已被注册，请更换一个昵称");
        }
        // 创建账户
        User user = new User();
        user.set(User.MOBILE,mobile);
        // 密码加盐 hash
        String salt = HashKit.generateSaltForSha256();
        user.set(User.SALT,salt);
        if (user_type==User.USER_TYPE_PROV){
            password = HashKit.sha256(salt + password);
            user.set(User.PASSWORD,password);
        }
        user.set(User.STATUS, User.USER_STATUS_NORMAL);
        user.set(User.PHOTO,User.DEFAULT_PHOTO);
        if (user_type==User.USER_TYPE_FAIR){
            user.set(User.USER_TYPE,User.USER_TYPE_FAIR);
        }
        if (user.save()) {
            return Ret.ok("id",user.get(User.ID));
        } else {
            return Ret.fail("msg", "注册失败，account 保存失败，请告知管理员");
        }
    }

    /**
     * 发送手机验证码
     */
    public Ret sendAuthCode(String mobile,String ip){
        //防止恶意发送验证码
        //缓存过期时间为5分钟， 5分钟内超过5次就不允许发送了
        Integer count=CacheKit.get(User.AUTH_CODE_CACHENAME,ip+mobile+"_count");
        if (null != count){
            Integer errorCount = PropKit.getInt("authcode.error.count");
            if (count>=errorCount){
                return Ret.fail("msg", "短信发送次数太频繁，请稍后再试");
            }else{
                CacheKit.put(User.AUTH_CODE_CACHENAME,ip+mobile+"_count",++count);
            }
        }
        //防止恶意发送验证码结束
        int code=(int)((Math.random()*9+1)*100000);
        CacheKit.put(User.AUTH_CODE_CACHENAME,ip+mobile,code);
        if (SendSmsMsg.isSend){
            //发送短信验证码
            if (SendSmsMsg.send(mobile,code+"")){
                return Ret.ok();
            }else{
                return Ret.fail();
            }
        }else {
            return Ret.ok("code",code);
        }
    }

    /**
     * 验证手机验证码
     */
    public boolean authCode(String mobile,String ip,int code,boolean flag){
        int cacheCode=CacheKit.get(User.AUTH_CODE_CACHENAME,ip+mobile);
        if (code==cacheCode){
            if (flag){
                CacheKit.remove(User.AUTH_CODE_CACHENAME,ip+mobile);
            }
            return true;
        }else{
            return false;
        }

    }

    /**
     * 找回密码发送验证码
     * @param mobile
     * @param ip
     * @return
     */
    public Ret sendAuthCodeByPasswordBack(String mobile,String ip,Integer user_type){
        if (isMobileExists(mobile,user_type)){
            return sendAuthCode(mobile,ip);
        }else{
            return Ret.fail("msg","用户不存在");
        }
    }

    /**
     * 保存认证信息
     * @param auth
     * @throws ValidateException 
     */
    public void save(Authenticate auth) throws ValidateException{
        
    	
    	Validator validator = new Validator();
    	
//    	validateRequired("authenticate.company_name", "companyNameMsg", "公司名称不能为空");
//		validateRequired("authenticate.company_address", "companyAddressMsg", "公司地址不能为空");
//		validateRequired("authenticate.company_charge", "companyChargeMsg", "法人姓名不能为空");
//		validateRequired("authenticate.company_charge_phone", "chargePhoneMsg", "法人手机号码不能为空");
//		validateRequired("authenticate.company_license", "licenseMsg", "法人手机号码不能为空");
//		validateRequired("authenticate.legal_idcard_front", "idcardFrontMsg", "法人手机号码不能为空");
//		validateRequired("authenticate.legal_idcard_tails", "idcardTailsMsg", "法人手机号码不能为空");
//		validateRequired("authenticate.charge_card", "chargeCardMsg", "法人手机号码不能为空");
//		validateRegex("authenticate.company_charge_phone",REGEX_MOBILE,"chargePhoneMsg","法人手机号码格式不正确");

    	
    	validator.addRule(new StringLengthBetween(auth.getStr(Authenticate.COMPANY_NAME), "公司名称只能是1-50个字符",1,50));
    	validator.addRule(new StringLengthBetween(auth.getStr(Authenticate.COMPANY_ADDRESS), "公司地址只能是1-50个字符",1,50));
    	validator.addRule(new StringLengthBetween(auth.getStr(Authenticate.COMPANY_CHARGE), "法人姓名只能是1-50个字符",1,50));
    	validator.addRule(new StringMustBeMobile(auth.getStr(Authenticate.COMPANY_CHARGE_PHONE), "法人手机号码格式不正确"));
    	validator.addRule(new StringMustBeRequired(auth.getStr(Authenticate.COMPANY_LICENSE), "营业执照不能为空"));
    	validator.addRule(new StringMustBeRequired(auth.getStr(Authenticate.LEGAL_IDCARD_FRONT), "身份证正面图片不能为空"));
    	validator.addRule(new StringMustBeRequired(auth.getStr(Authenticate.LEGAL_IDCARD_TAILS), "身份证反面图片不能为空"));
    	validator.addRule(new StringMustBeRequired(auth.getStr(Authenticate.CHARGE_CARD), "负责人名片不能为空"));
    	
    	validator.excute();
    	Authenticate isNull = authDao.findFirst("select * from fair_user_authenticate where user_id=?",auth.getLong(Authenticate.USER_ID));
        //认证信息不存在
        if (isNull==null){
            auth.save();
        }else{
            //认证信息存在
            //如果该信息的状态为打回状态
            if (isNull.getInt(Authenticate.STATUS)==Authenticate.STATUS_FAILURE){
                //更新改条信息
//                isNull._setAttrs(auth);
                //设置状态为待审核
                auth.set(Authenticate.STATUS,Authenticate.STATUS_APPROVING);
                auth.update();
            }
        }
    }


    /**
     * 找回密码
     * @param mobile
     * @param password
     */
    public Ret passwordBack(String mobile,String password,Integer user_type){
        if (StrKit.isBlank(mobile) || StrKit.isBlank(password)) {
            return Ret.fail("msg", "手机号码或密码不能为空");
        }
        password = password.trim();
        mobile = mobile.trim();

        if (mobile.contains(" ") || mobile.contains("　")) { // 检测是否包含半角或全角空格
            return Ret.fail("msg", "手机号码不能包含空格");
        }
        if (!isMobileExists(mobile,user_type)) {
            return Ret.fail("msg", "用户不存在");
        }
        User user=loginService.findByMobile(mobile,user_type);
        if (user !=null ){
            password = HashKit.sha256(user.get(User.SALT) + password);
            user.set(User.PASSWORD,password);
            user.update();
            return Ret.ok();
        }else{
           return  Ret.fail("msg", "用户不存在");
        }

    }

    /**
     * 根据用户ID获取用户信息
     * @return
     */
    public User findById(int id){
        return User.dao.findById(id);
    }





}
